package com.fsquare.controller.entity;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.broadleafcommerce.admin.web.controller.entity.AdminOrderController;
import org.broadleafcommerce.common.exception.ServiceException;
import org.broadleafcommerce.common.presentation.client.SupportedFieldType;
import org.broadleafcommerce.core.order.domain.Order;
import org.broadleafcommerce.core.order.service.OrderService;
import org.broadleafcommerce.core.order.service.type.OrderStatus;
import org.broadleafcommerce.openadmin.web.controller.entity.AdminBasicEntityController;
import org.broadleafcommerce.openadmin.web.form.component.ListGrid;
import org.broadleafcommerce.openadmin.web.form.entity.EntityForm;
import org.broadleafcommerce.openadmin.web.form.entity.Field;
import org.broadleafcommerce.openadmin.web.form.entity.FieldGroup;
import org.broadleafcommerce.openadmin.web.form.entity.Tab;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.fsquare.admin.common.Utils;
import com.fsquare.service.invoice.InvoiceService;
import com.itextpdf.text.pdf.PdfStructTreeController.returnType;


//@Controller("blAdminOrderController")
@RequestMapping("/" + ExtAdminOrderController.SECTION_KEY)
public class ExtAdminOrderController extends AdminOrderController {
    
    protected static final String SECTION_KEY = "order";
    
    @Resource(name = "blOrderService")
    protected OrderService orderService;
    
    @Resource(name = "fsquareInvoiceService")
    protected InvoiceService invoiceService;
    
   
	@Override
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String viewEntityForm(HttpServletRequest request, HttpServletResponse response, Model model,
        @PathVariable  Map<String, String> pathVars,
        @PathVariable(value="id") String id) throws Exception {
    	
    	String returnPath = super.viewEntityForm(request, response, model, pathVars, id);
    	Order order = orderService.findOrderById(Long.parseLong(id));
    	
    	EntityForm entityForm = (EntityForm) model.asMap().get("entityForm");
    	
    	
    	if (OrderStatus.SUBMITTED.equals(order.getStatus())) {
    		
    		for(Tab tab : entityForm.getTabs()) {
    			System.out.println("***"+tab.getTitle());
    			if("General".equals(tab.getTitle())) {
    				FieldGroup group = new FieldGroup();
	        		group.setTitle("Actions");
	        		group.setOrder(1);
	        		
	        		Field updateorderstatusField = new Field();
	        		updateorderstatusField.setName("Mark as Complete");
	        		updateorderstatusField.setFriendlyName("Mark as Complete");
	        		updateorderstatusField.setDisplayValue("Mark as Complete");
	        		updateorderstatusField.setFieldType("updateorderstatus");
	        		updateorderstatusField.setValue(order.getId().toString());
	        		
	        		group.addField(updateorderstatusField);
	        		
	        		tab.getFieldGroups().add(group);
    			}
    		}
    		
    		FieldGroup group = new FieldGroup();
    		group.setTitle("Downloadable");
    		group.setOrder(1);
    		
    		Field orderField = new Field();
    		orderField.setName("order");
    		orderField.setFriendlyName("order_file");
    		orderField.setDisplayValue("order");
    		orderField.setFieldType("download");
    		orderField.setValue(order.getId().toString());
    		group.addField(orderField);
    		
    		Field invoiceField = new Field();
    		invoiceField.setName("invoice");
    		invoiceField.setFriendlyName("invoice_file");
    		invoiceField.setDisplayValue("invoice");
    		invoiceField.setFieldType("download");
    		invoiceField.setValue(order.getId().toString());
    		group.addField(invoiceField);
   
    		Field addressField = new Field();
    		addressField.setName("address");
    		addressField.setFriendlyName("address_file");
    		addressField.setDisplayValue("address");
    		addressField.setFieldType("download");
    		addressField.setValue(order.getId().toString());
    		group.addField(addressField);
    		
    		Tab filesTab = new Tab();
    		filesTab.setTitle("Files");
    		filesTab.setOrder(Integer.MAX_VALUE);
    		filesTab.setTabClass("files-tab");
    		
    		filesTab.getFieldGroups().add(group);
    		
   
    		entityForm.getTabs().add(filesTab);
    	}

    	return returnPath;
    }
	
	
    @RequestMapping(value = "/{id}/{action}", method = RequestMethod.PATCH)
    public String performAction(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable(value="id") String id) throws Exception {
		return "";
	}
	
	@RequestMapping(value = "/download/{fileType}/{orderId}", method = RequestMethod.GET)
	public void getFile(@PathVariable("fileType") String fileType, @PathVariable("orderId") String orderId, HttpServletResponse response) {
//	    try {
//	      // get your file as InputStream
//	      InputStream is = ...;
//	      // copy it to response's OutputStream
//	      IOUtils.copy(is, response.getOutputStream());
		response.setContentType("application/pdf");
//	      response.flushBuffer();
//			
//	    } catch (IOException ex) {
//	      log.info("Error writing file to output stream. Filename was '" + fileName + "'");
//	      throw new RuntimeException("IOError writing file to output stream");
//	    }

	}
}
